import React from 'react';
import { Breadcrumb } from 'antd';
import { useLocation } from 'react-router';
import { Link } from 'react-router-dom';
import { MenuItem as MenuItemType, SubMenuItem, menuMap } from '~/components/SideMenu/sideMenuUtils';

type MenuItem = MenuItemType | SubMenuItem;
const getMenuItem = (pathName: string) => menuMap.get(pathName);

export const ProjectBreadcrumb = () => {
  const location = useLocation();

  const getCurrentMenuKeys = () => {
    let item: MenuItem | undefined = getMenuItem(location.pathname);
    const arr = [];

    while (item) {
      arr.unshift({
        name: item.name,
        path: item.path,
      });
      item = item.parentItem;
    }

    if (arr.length) {
      delete arr[arr.length - 1].path;
    }

    return arr;
  };

  const breadList = getCurrentMenuKeys();

  return (
    <Breadcrumb className="mt-2 mb-2">
      {
        breadList.map((v) => (v.path
          ? <Breadcrumb.Item key={v.name}>
            <Link
              to={v.path}
              className="no-underline cursor-pointer"
            >
              {v.name}
            </Link>
          </Breadcrumb.Item>
          : <Breadcrumb.Item
            key={v.name}
          >
            {v.name}
          </Breadcrumb.Item>
        ))}
    </Breadcrumb>
  );
};
